package com.woniuxy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.CustomerManagement;
import com.woniuxy.entity.Department;
import com.woniuxy.entity.DriverPickupAddress;
import com.woniuxy.entity.PowerUser;
import com.woniuxy.entity.dto.NormalOrderDTO;
import com.woniuxy.mapper.OrderMapper;
import com.woniuxy.service.OrderService;
import com.woniuxy.service.PowerUserService;
import com.woniuxy.util.*;
import org.apache.ibatis.javassist.runtime.DotClass;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ExportService exportService;

    @Override
    public ResponseData<?> queryCustomerOrder(PageData<NormalOrderDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<NormalOrderDTO> normalOrderDTOS = orderMapper.queryCustomerOrder(pageData.getParam());
        PageInfo pageInfo = new PageInfo(normalOrderDTOS);
        return new ResponseData<>().ok(pageInfo);
    }

    @Override
    public ResponseData<?> queryUserOrder(PageData<NormalOrderDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<NormalOrderDTO> normalOrderDTOS = orderMapper.queryUserOrder(pageData.getParam());
        PageInfo pageInfo = new PageInfo(normalOrderDTOS);
        return new ResponseData<>().ok(pageInfo);
    }

    @Override
    public ResponseData<?> queryBasicDetail(String id) {
        NormalOrderDTO normalOrderDTO = orderMapper.queryBasicDetail(id);
        return new ResponseData<>().ok(normalOrderDTO);
    }

    @Override
    public ResponseData<?> querySendDetail(String id) {
        NormalOrderDTO normalOrderDTO = orderMapper.querySendDetail(id);
        return new ResponseData<>().ok(normalOrderDTO);
    }

    @Override
    public ResponseData<?> queryDeliveryDetail(String id) {
        NormalOrderDTO normalOrderDTO = orderMapper.queryDeliveryDetail(id);
        return new ResponseData<>().ok(normalOrderDTO);
    }

    @Override
    public ResponseData<?> queryGoodsDetail(String id) {
        List<NormalOrderDTO> normalOrderDTOS = orderMapper.queryGoodsDetail(id);
        return new ResponseData<>().ok(normalOrderDTOS);
    }

    @Override
    public ResponseData<?> queryCostDetail(String id) {
        NormalOrderDTO normalOrderDTO = orderMapper.queryCostDetail(id);
        return new ResponseData<>().ok(normalOrderDTO);
    }

    public ResponseData<?> createSnowId() {
        SnowflakeIdGenerator sg = new SnowflakeIdGenerator();
        String orderNum = String.valueOf(sg.nextId());
        String prefixedOrderNum = "D" + orderNum;
        return new ResponseData<>().ok(prefixedOrderNum);
    }

    @Override
    public ResponseData<?> queryCustomer() {
        List<CustomerManagement> customerManagements = orderMapper.queryCustomer();
        return new ResponseData<>().ok(customerManagements);
    }

    @Override
    public ResponseData<?> queryGoods() {
        List<NormalOrderDTO> normalOrderDTOS = orderMapper.queryGoods();
        return new ResponseData<>().ok(normalOrderDTOS);
    }

    @Override
    public ResponseData<?> addGoods(List<NormalOrderDTO> normalOrderDTOS) {
        List<NormalOrderDTO> normalOrderDTOS1 = orderMapper.queryOrderGoods(normalOrderDTOS.get(0).getId());

        if (!normalOrderDTOS1.isEmpty()) {
            // 创建一个列表来存储需要添加的新商品
            List<NormalOrderDTO> newGoodsToAdd = new ArrayList<>();

            for (NormalOrderDTO dto : normalOrderDTOS) {
                boolean found = false;
                // 在数据库查询结果中找到对应的订单商品
                for (NormalOrderDTO dbDto : normalOrderDTOS1) {
                    if (dto.getGoodsId().equals(dbDto.getGoodsId())) {
                        // 如果找到对应的订单商品，则更新smallGoodsCount
                        Integer a = dbDto.getGoodsSmallCount();
                        Integer b = dto.getGoodsSmallCount();
                        dto.setGoodsSmallCount(a + b);
                        orderMapper.updateGoodsSmallCount(dto);
                        found = true;
                        break; // 找到匹配项后退出内层循环
                    }
                }
                if (!found) {
                    // 如果没有找到匹配的商品，则添加到新商品列表中
                    newGoodsToAdd.add(dto);
                }
            }

            // 添加新商品列表中的商品
            if (!newGoodsToAdd.isEmpty()) {
                orderMapper.addGoods(newGoodsToAdd);
            }
        } else {
            // 如果数据库中没有相关商品，则直接添加所有商品
            List<NormalOrderDTO> normalOrderDTOS2 = new ArrayList<>();
            for (NormalOrderDTO normalOrderDTO : normalOrderDTOS) {
                if (normalOrderDTO.getGoodsSmallCount() != null && normalOrderDTO.getGoodsSmallCount() != 0) {
                    normalOrderDTOS2.add(normalOrderDTO);
                }
            }
            if (!normalOrderDTOS2.isEmpty()) {
                orderMapper.addGoods(normalOrderDTOS2);
            }
        }

        return new ResponseData<>().ok();
//        List<NormalOrderDTO> normalOrderDTOS1 = orderMapper.queryOrderGoods(normalOrderDTOS.get(0).getId());
//        if (!normalOrderDTOS1.isEmpty()){
//            for (NormalOrderDTO dto : normalOrderDTOS) {
////                boolean found = false;
//                // 在数据库查询结果中找到对应的订单商品
//                for (NormalOrderDTO dbDto : normalOrderDTOS1) {
//                    if (dto.getGoodsId().equals(dbDto.getGoodsId())) {
//                        // 如果找到对应的订单商品，则更新smallGoodsCount
//                        Integer a =  dbDto.getGoodsSmallCount();
//                        Integer b = dto.getGoodsSmallCount();
//                        dto.setGoodsSmallCount(a + b);
//                        orderMapper.updateGoodsSmallCount(dto);
////                        found = true;
////                        break; // 找到匹配项后退出内层循环
//                    }else {
//                        List<NormalOrderDTO> normalOrderDTOS2 = new ArrayList<>();
//                        normalOrderDTOS2.add(dto);
//                        orderMapper.addGoods(normalOrderDTOS2);
//                    }
//                }
//            }
//            return  new ResponseData<>().ok();
//        }else {
//
//            List<NormalOrderDTO> normalOrderDTOS2 = new ArrayList<>();
//            for (NormalOrderDTO normalOrderDTO : normalOrderDTOS) {
//                if (normalOrderDTO.getGoodsSmallCount() != null && normalOrderDTO.getGoodsSmallCount() != 0 ){
//                    normalOrderDTOS2.add(normalOrderDTO);
//                }
//            }
//            if (!normalOrderDTOS2.isEmpty()){
//                orderMapper.addGoods(normalOrderDTOS2);
//            }
//            return new ResponseData<>().ok();
//        }


    }

    @Override
    public ResponseData<?> queryGoods2(String id) {
        List<NormalOrderDTO> normalOrderDTOS = orderMapper.queryGoods2(id);
        return new ResponseData<>().ok(normalOrderDTOS);
    }

    @Override
    public ResponseData<?> createOrder(NormalOrderDTO normalOrderDTO) throws ParseException {
        if (normalOrderDTO.getCustomerId() == null) {
            normalOrderDTO.setOrderSource("0");
            normalOrderDTO.setContract("0");
        }
        if (normalOrderDTO.getUserId() == null) {
            normalOrderDTO.setOrderSource("1");
            normalOrderDTO.setContract("1");
        }
        //客户订单逻辑


        NormalOrderDTO addDriverPickUp = new NormalOrderDTO();//司机提货表添加对象
        addDriverPickUp.setCustomerId(normalOrderDTO.getCustomerId());//customer_id
        addDriverPickUp.setDpaAddress3(normalOrderDTO.getDpaAddress3());//address1  address2
        addDriverPickUp.setFaHuoAddress(normalOrderDTO.getFaHuoAddress());
        orderMapper.addDriverPickUp(addDriverPickUp);

        NormalOrderDTO addDeliveryAddress = new NormalOrderDTO();//收货地址表添加对象
        addDeliveryAddress.setCustomerId(normalOrderDTO.getCustomerId());//customer_id
        addDeliveryAddress.setCdaAddress3(normalOrderDTO.getCdaAddress3());//address1 address2
        orderMapper.addDeliveryAddress(addDeliveryAddress);

        //处理时间部分
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
        SimpleDateFormat outputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        //算货物体积
        //算货物重量
        //算货物数量
        List<NormalOrderDTO> normalOrderDTOS = orderMapper.queryOrderGoods(normalOrderDTO.getSnowId());
        Integer count=0;
        Integer volume = 0;
        Integer weight = 0;
        if (normalOrderDTOS != null) {
            for (NormalOrderDTO orderDTO : normalOrderDTOS) {
                count = count + orderDTO.getGoodsSmallCount();
                volume = volume +orderDTO.getGoodsVolume();
                weight = weight + orderDTO.getGoodsWeight();
            }
        }
        //算费用合计
        BigDecimal totalFees = BigDecimal.ZERO;
        totalFees = totalFees.add(normalOrderDTO.getTransportationFee());
        totalFees = totalFees.add(normalOrderDTO.getInsuranceFee());
        totalFees = totalFees.add(normalOrderDTO.getPackagingFee());
        totalFees = totalFees.add(normalOrderDTO.getLoadingFee());
        totalFees = totalFees.add(normalOrderDTO.getTransferFee());
        totalFees = totalFees.add(normalOrderDTO.getServiceFee());
        totalFees = totalFees.add(normalOrderDTO.getOtherFees());

        NormalOrderDTO addOrderDTO = new NormalOrderDTO();//订单表添加对象
        addOrderDTO.setId(normalOrderDTO.getSnowId());//id
        addOrderDTO.setCustomerId(normalOrderDTO.getCustomerId());//customer_id
        addOrderDTO.setOrderType(normalOrderDTO.getOrderType());//order_type
        addOrderDTO.setGoodsType(normalOrderDTO.getGoodsType());//goods_type
//        addOrderDTO.setOrderCreatedTime(formattedDate);//order_create_time
        addOrderDTO.setPickupAddressId(addDriverPickUp.getId());//pickup_address_id
        addOrderDTO.setDeliveryAddressId(addDeliveryAddress.getId());//delivery_address_id

        addOrderDTO.setTotalFee(totalFees);//total_fee
        addOrderDTO.setAllVolume(volume.toString());//all_volume
        addOrderDTO.setAllWeight(weight.toString());//all_weight
        addOrderDTO.setGoodsCount(count);//goods_count
        Long userId = UserContext.getUserId();
        addOrderDTO.setPoweruserId(userId.intValue());//poweruser_id
        addOrderDTO.setRemarks(normalOrderDTO.getRemarks());//remarks
//        ZonedDateTime zonedDateTime1 = ZonedDateTime.parse(normalOrderDTO.getExpectedShipmentTime(), inputFormatter);
//        String formattedDate1 = outputFormatter.format(Date.from(zonedDateTime1.toInstant()));
//        ZonedDateTime zonedDateTime2 = ZonedDateTime.parse(normalOrderDTO.getExpectedDeliveryTime(), inputFormatter);
//        String formattedDate2 = outputFormatter.format(Date.from(zonedDateTime2.toInstant()));
//        addOrderDTO.setExpectedShipmentTime(formattedDate1);//expected_shipment_time
//        addOrderDTO.setExpectedDeliveryTime(formattedDate2);//expected_delivery_time
        addOrderDTO.setBillingMethod(normalOrderDTO.getBillingMethod());//billing_method
        addOrderDTO.setPaymentMethod(normalOrderDTO.getPaymentMethod());//payment_method
        addOrderDTO.setTransportationFee(normalOrderDTO.getTransportationFee());//transportation_fee
        addOrderDTO.setInsuranceFee(normalOrderDTO.getInsuranceFee());//insurance_fee
        addOrderDTO.setPackagingFee(normalOrderDTO.getPackagingFee());//packaging_fee
        addOrderDTO.setLoadingFee(normalOrderDTO.getLoadingFee());//loading_fee
        addOrderDTO.setTransferFee(normalOrderDTO.getTransferFee());//transfer_fee
        addOrderDTO.setServiceFee(normalOrderDTO.getServiceFee());//service_fee
        addOrderDTO.setOtherFees(normalOrderDTO.getOtherFees());//other_fees
        if (normalOrderDTO.getCustomerId() == null) {
            addOrderDTO.setOrderSource("0");
            addOrderDTO.setContract("0");
        }
        if (normalOrderDTO.getUserId() == null) {
            addOrderDTO.setOrderSource("1");
            addOrderDTO.setContract("1");
        }
        List<NormalOrderDTO> normalOrderDTOS1 = orderMapper.queryOrderGoods(normalOrderDTO.getSnowId());
        if (normalOrderDTOS1 == null || normalOrderDTOS1.isEmpty()) {
            // 如果集合为空，返回失败响应
            return new ResponseData<>().fail(ResponseEnum.ORDER_ERROR);
        }
        orderMapper.addOrder(addOrderDTO);

        return new ResponseData<>().ok();
    }

    @Override
    public ResponseData<?> scheduling(NormalOrderDTO normalOrderDTO) {
        SnowflakeIdGenerator sg = new SnowflakeIdGenerator();
        String orderNum = String.valueOf(sg.nextId());
        String prefixedOrderNum = "Y" + orderNum;  //运单的雪花ID
        NormalOrderDTO orderDTO = new NormalOrderDTO();
        orderDTO.setId(normalOrderDTO.getId());
        orderDTO.setWaybillId(prefixedOrderNum);
        Long userId = UserContext.getUserId();
        orderDTO.setPoweruserId(userId.intValue());
        orderDTO.setPickupAddressId(normalOrderDTO.getPickupAddressId());
        orderDTO.setDeliveryAddressId(normalOrderDTO.getDeliveryAddressId());
        orderMapper.updateOrderWayId(orderDTO);
        orderMapper.addWayid(orderDTO);
        return new ResponseData<>().ok();
    }


    @Override
    public ResponseData<?> combinedOrder(List<NormalOrderDTO> normalOrderDTOS) throws ParseException {
        String firstCustomerId = null;
        Integer firstDpaAddress2 = null;
        Integer firstCdaAddress2 = null;
        String firstFaHuoAddress = null;
        for (NormalOrderDTO normalOrderDTO : normalOrderDTOS) {
            String customerId = normalOrderDTO.getCustomerId();
            Integer dpaAddress2 = normalOrderDTO.getDpaAddress2();
            Integer cdaAddress2 = normalOrderDTO.getCdaAddress2();
            String faHuoAddress = normalOrderDTO.getFaHuoAddress();
            String waybillId= normalOrderDTO.getWaybillId(); // 获取wayId
            if (firstCustomerId == null) {
                // 记录第一个customerId
                firstCustomerId = customerId;
                firstDpaAddress2 = dpaAddress2;
                firstCdaAddress2 = cdaAddress2;
                firstFaHuoAddress = faHuoAddress;
            } else  {
                // 检查后续的customerId是否与第一个相同
                if (!firstCustomerId.equals(customerId)) {
                    return new ResponseData<>().fail(ResponseEnum.COMBINED_ORDER_ERROR1);
                }
                if (waybillId != null) {
                    // 如果任意一个wayId不为空，返回失败
                    return new ResponseData<>().fail(ResponseEnum.COMBINED_ORDER_ERROR2);
                }
                // 检查后续的dpaAddress2是否与第一个相同
                if (firstDpaAddress2 != dpaAddress2) {
                    return new ResponseData<>().fail(ResponseEnum.COMBINED_ORDER_ERROR3);
                }
                if (firstCdaAddress2 != cdaAddress2 || !firstFaHuoAddress.equals(faHuoAddress)) {
                    return new ResponseData<>().fail(ResponseEnum.COMBINED_ORDER_ERROR4);
                }
            }
        }

        SnowflakeIdGenerator sg = new SnowflakeIdGenerator();
        String orderNum = String.valueOf(sg.nextId());
        String prefixedOrderNum = "D" + orderNum;



        //处理订单货物表逻辑
        List<String> ids = new ArrayList<>();
        //删除提货地址表集合
        List<String> ids1 = new ArrayList<>();
        //删除收货地址表集合
        List<String> ids2 = new ArrayList<>();
        for (NormalOrderDTO normalOrderDTO : normalOrderDTOS) {
            ids.add(normalOrderDTO.getId());
            ids1.add(normalOrderDTO.getPickupAddressId());
            ids2.add(normalOrderDTO.getDeliveryAddressId());
        }
        List<NormalOrderDTO> normalOrderDTOS1 = orderMapper.queryGoodsByGroup(ids);
        for (NormalOrderDTO normalOrderDTO : normalOrderDTOS1) {
            normalOrderDTO.setId(prefixedOrderNum);
        }
        orderMapper.addGoods(normalOrderDTOS1);
//        orderMapper.batchDelGoods(ids);
//        orderMapper.batchDelPickupAddress(ids1);
//        orderMapper.batchDelDeliveryAddress(ids2);
        NormalOrderDTO orderDTO = new NormalOrderDTO();
        orderDTO.setCustomerId(normalOrderDTOS.get(0).getCustomerId());
        orderDTO.setFaHuoAddress(normalOrderDTOS.get(0).getFaHuoAddress());
        List<Integer> dpaAddress = new ArrayList<>();
        dpaAddress.add(normalOrderDTOS.get(0).getDpaAddress1());
        dpaAddress.add(normalOrderDTOS.get(0).getDpaAddress2());
        orderDTO.setDpaAddress3(dpaAddress);
        List<Integer> cdaAddress = new ArrayList<>();
        cdaAddress.add(normalOrderDTOS.get(0).getCdaAddress1());
        cdaAddress.add(normalOrderDTOS.get(0).getCdaAddress2());
        orderDTO.setCdaAddress3(cdaAddress);


        BigDecimal transportationFee = BigDecimal.ZERO;
        BigDecimal insuranceFee = BigDecimal.ZERO;
        BigDecimal packagingFee = BigDecimal.ZERO;
        BigDecimal loadingFee = BigDecimal.ZERO;
        BigDecimal transferFee = BigDecimal.ZERO;
        BigDecimal serviceFee = BigDecimal.ZERO;
        BigDecimal otherFees = BigDecimal.ZERO;
        for (NormalOrderDTO normalOrderDTO : normalOrderDTOS) {
            transportationFee = transportationFee.add(normalOrderDTO.getTransportationFee());
            insuranceFee = insuranceFee.add(normalOrderDTO.getInsuranceFee());
            packagingFee = packagingFee.add(normalOrderDTO.getPackagingFee());
            loadingFee = loadingFee.add(normalOrderDTO.getLoadingFee());
            transferFee = transferFee.add(normalOrderDTO.getTransferFee());
            serviceFee = serviceFee.add(normalOrderDTO.getServiceFee());
            otherFees = otherFees.add(normalOrderDTO.getOtherFees());
        }
        orderDTO.setTransportationFee(transportationFee);
        orderDTO.setInsuranceFee(insuranceFee);
        orderDTO.setPackagingFee(packagingFee);
        orderDTO.setLoadingFee(loadingFee);
        orderDTO.setTransferFee(transferFee);
        orderDTO.setServiceFee(serviceFee);
        orderDTO.setOtherFees(otherFees);

        orderDTO.setSnowId(prefixedOrderNum);
        orderDTO.setOrderType(normalOrderDTOS.get(0).getOrderType());
        orderDTO.setGoodsType(normalOrderDTOS.get(0).getGoodsType());
        Long userId = UserContext.getUserId();
        orderDTO.setPoweruserId(userId.intValue());
        orderDTO.setRemarks(normalOrderDTOS.get(0).getRemarks());
        orderDTO.setBillingMethod(normalOrderDTOS.get(0).getBillingMethod());
        orderDTO.setPaymentMethod(normalOrderDTOS.get(0).getPaymentMethod());
        orderDTO.setOrderSource("1");
        orderDTO.setContract("1");
        createOrder(orderDTO);
        orderMapper.updateOrderSource(ids,prefixedOrderNum);
        orderMapper.updateEmployeeId(prefixedOrderNum);
        return new ResponseData<>().ok();
    }


    @Override
    public ResponseData<?> splitOrder(NormalOrderDTO normalOrderDTO) {
        orderMapper.updateOrderSourceAndEmployeeId(normalOrderDTO.getId());
        orderMapper.delOrder(normalOrderDTO.getId());
        return new ResponseData<>().ok();
    }

    @Override
    public ResponseData<?> cancelOrder(NormalOrderDTO normalOrderDTO) {
        orderMapper.updateOrderStatus(normalOrderDTO.getId());
        return new ResponseData<>().ok();
    }

    @Override
    public ResponseData<?> batchCancelOrder(List<NormalOrderDTO> normalOrderDTOS) {
        List<String> ids = new ArrayList<>();
        for (NormalOrderDTO normalOrderDTO : normalOrderDTOS) {
            if (normalOrderDTO.getWaybillId() != null){
                return new ResponseData<>().fail(ResponseEnum.FAIL);
            }
            ids.add(normalOrderDTO.getId());
        }
        orderMapper.batchCancelOrder(ids);
        return  new ResponseData<>().ok();
    }

    @Override
    public ResponseData<?> exportYiData(HttpServletResponse response) {
        List<Map<String, Object>> yiData = orderMapper.queryException2(null);

        // 字段名与中文表头的映射关系
        Map<String, String> fieldToChineseMap = new HashMap<>();
        exportService.exportDynamicDataToExcel(response, yiData, fieldToChineseMap);

        return new ResponseData<>().ok();
    }
}
